package cmd

import (
	"log"
	"os"
	"webssh/config"
	"webssh/src"
	"webssh/src/logger"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands

var rootCmd = &cobra.Command{
	Use:   "hpc-adapter",
	Short: "hpc-adapter.",
	Run: func(cmd *cobra.Command, args []string) {
		config.InitConfig(cfgFile)
		run(":" + viper.GetString("server.port"))
	},
}

func run(addr string) {
	defer func() {
		if r := recover(); r != nil {
			log.Fatalf("panic: %v", r)
		}
	}()
	logger.Log = logger.New(viper.GetString("server.port"))
	server := src.NewServer()
	server.Run(addr)
}

func init() {
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is /etc/gcp/sshweb.yaml)")
}

func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}
